//
//  YSReadParser.m
//  YSBookRead
//
//  Created by Kyson on 2018/11/6.
//  Copyright © 2018 YangShen. All rights reserved.
//

#import "YSReadParser.h"
#import "YSReadBookModel.h"
#import "YSStorageManager.h"
#import "YSReadHelper.h"
#import "YSBookChapterModel.h"

@implementation YSReadParser

+ (void)parserLocalBook:(NSString *)path complete:(void(^)(YSReadBookModel *readBook))complete {
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        YSReadBookModel *readBook = [self parserLocalBook:path];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            !complete ?: complete(readBook);
        });
    });
}

+ (YSReadBookModel *)parserLocalBook:(NSString *)path {
    if (path.length == 0) {
        NSLog(@"---没有路径---");
        return nil;
    }
    
    NSString *bookID = path.lastPathComponent.stringByDeletingPathExtension;
    
    YSReadBookModel *readBook = [YSStorageManager getReadBook:bookID];
    if (!readBook) {
        readBook = [YSReadBookModel readBookWithBookID:bookID];
        readBook.bookName = bookID;

        // 解析数据
        NSString *content = [self encodePath:path];

        // 解析章节列表
        [self parserContent:content bookID:bookID];

        readBook.isLocalBook = YES;

        [YSStorageManager saveReadBook:readBook];
    }
    
    return readBook;
}

#pragma mark - Private Method

/// 得到路径下的内容
+ (NSString *)encodePath:(NSString *)path {
    
    NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    
    if (content.length == 0) {
        content = [NSString stringWithContentsOfFile:path encoding:0x80000632 error:nil];
    }
    
    if (content.length == 0) {
        content = [NSString stringWithContentsOfFile:path encoding:0x80000631 error:nil];
    }
    
    if (content.length == 0) {
        NSLog(@"无法解析%@下面的数据", path);
        content = @"";
    }
    
    return [content stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

/// 解析数据 -> 章节
+ (void)parserContent:(NSString *)content bookID:(NSString *)bookID {
    NSMutableArray *chapterList = [NSMutableArray array];
    
    // 正则
    NSString *parten = @"第[0-9一二三四五六七八九十百千]*[章回].*";
    
    // 搜索结果数组    
    NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:parten options:NSRegularExpressionCaseInsensitive error:nil];
    NSArray *results = [expression matchesInString:content options:NSMatchingReportCompletion range:NSMakeRange(0, content.length)];
    
    if (results.count == 0) {
        // 创建章节内容模型
        YSBookChapterModel *chapterModel = [[YSBookChapterModel alloc] init];
        chapterModel.bookID = bookID;
        chapterModel.chapterIndex = 0;
        chapterModel.chapterID = @"1";
        chapterModel.chapterName = @"开始";
        chapterModel.haveCache = YES;
        // 内容
        NSString *formatContent = [YSReadHelper formartChpaterContent:content];
        [YSStorageManager saveBookChapterBody:chapterModel.bookID chapterID:chapterModel.chapterID body:formatContent];

        // 添加章节列表模型
        [chapterList addObject:chapterModel];

        [YSStorageManager saveBookChapterList:chapterList bookID:bookID summaryID:nil];
        return;
    }

    // 解析搜索结果
    NSRange lastRange = NSMakeRange(0, 0);
    NSInteger count = results.count;
    YSBookChapterModel *lastChapterModel;

    for (NSInteger i = 0; i <= count; i++) {
        // 章节数量分析:
        // count + 1  = 搜索到的章节数量 + 最后一个章节,
        // 1 + count + 1  = 第一章前面的前言内容 + 搜索到的章节数量 + 最后一个章节
        NSLog(@"总章节数:%zd 当前解析:%zd", count+1, i+1);

        NSRange range = NSMakeRange(0, 0);
        NSInteger location = 0;

        if (i < count) {
            NSTextCheckingResult *result = results[i];
            range = result.range;
            location = range.location;
        }

        // 创建章节内容模型
        YSBookChapterModel *chapterModel = [[YSBookChapterModel alloc] init];
        chapterModel.bookID = bookID;
        chapterModel.chapterID = [NSString stringWithFormat:@"%zd", i+1];
        chapterModel.chapterIndex = i;

        NSString *formatContent;
        if (i == 0) { // 开头
            // 章节名
            chapterModel.chapterName = @"开始";
            // 内容
            formatContent = [YSReadHelper formartChpaterContent:[content substringToIndex:location]];

            // 记录
            lastRange = range;

            // 说不定没有内容 则不需要添加到列表
            if (formatContent.length == 0) { continue; }
        } else if (i == count) { // 结尾
            // 章节名
            chapterModel.chapterName = [content substringWithRange:lastRange];
            // 内容
            formatContent = [YSReadHelper formartChpaterContent:[content substringWithRange:NSMakeRange(lastRange.location, content.length - lastRange.location)]];
        } else { // 中间章节
            // 章节名
            chapterModel.chapterName = [content substringWithRange:lastRange];
            // 内容
            formatContent = [YSReadHelper formartChpaterContent:[content substringWithRange:NSMakeRange(lastRange.location, location - lastRange.location)]];
        }

        /// 存储章节内容
        [YSStorageManager saveBookChapterBody:chapterModel.bookID chapterID:chapterModel.chapterID body:formatContent];
        chapterModel.haveCache = YES;

        // 设置上下章ID
        chapterModel.prevChapterID = lastChapterModel.chapterID;
        lastChapterModel.nextChapterID = chapterModel.chapterID;

        // 添加章节列表模型
        [chapterList addObject:chapterModel];

        // 记录
        lastRange = range;
        lastChapterModel = chapterModel;
    }

    [YSStorageManager saveBookChapterList:chapterList bookID:bookID summaryID:nil];
}

@end
